﻿using System.Linq;
using InvestmentIntelligence.Logging.Core;
using InvestmentIntelligence.SchedulingService.Infrastructure;
using InvestmentIntelligence.TradingData.Adapters.Mus.Enums;
using InvestmentIntelligence.TradingData.Adapters.Mus.MarketIndicators.TrendIndicators;
using InvestmentIntelligence.TradingData.DataProcessing.DataResolvers;
using System.Collections.Generic;

namespace InvestmentIntelligence.TradingData.Adapters.Mus.DataGenerators
{
    class TradingDataGenerator : IScheduledTask
    {
        private readonly int _bookId;
        private readonly SecurityInfoMapper _securityInfoMapper;
        private readonly TimeSerieInfoMapper _timeSerieInfoMapper;

        public TradingDataGenerator(int bookId, SecurityInfoMapper securityInfoMapper, TimeSerieInfoMapper timeSerieInfoMapper)
        {
            _bookId = bookId;
            _securityInfoMapper = securityInfoMapper;
            _timeSerieInfoMapper = timeSerieInfoMapper;
        }

        public void Execute()
        {
            var indicators = new[] { new ExponentialMovingAverageIndicator() };
            var indicatorsResults = new Dictionary<int, List<TrendIndicatorResult>>();

            var securities = _securityInfoMapper.Get();
            foreach (var securityInfo in securities)
            {
                var securityId = securityInfo.Id;
                var timeSeries = _timeSerieInfoMapper.Get(securityId);
                
                var list = new List<TrendIndicatorResult>();
                indicatorsResults.Add(securityId, list);

                foreach (var indicator in indicators)
                {
                    list.Add(new TrendIndicatorResult
                    {
                        IndicatorType = indicator.Type,
                        Results = indicator.Indicate(securityId, timeSeries),
                    });
                }

                if (list.All(r => r.Results.All(rr => rr.Value == TrendActions.None)))
                {
                    _timeSerieInfoMapper.ReleaseData(securityId);
                }
            }

            var processor = new TrendIndicatorResultsProcessor(_bookId, _securityInfoMapper, _timeSerieInfoMapper);
            processor.Process(indicatorsResults);

            Log.Info("Trading data generated!");
        }
    }
}
